package com.example.translateappjava.Activity.MineFragmentActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.LinearLayout;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat; // <--- 添加这行
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.preference.PreferenceManager;

import com.example.translateappjava.R;

public class SettingsActivity extends AppCompatActivity {
    private static OnUIVersionChangeListener uiVersionChangeListener;

    private CheckBox checkBox1;
    private CheckBox checkBox2;
    private CheckBox checkBox3;
    private CheckBox checkBox4;
    private CheckBox checkBox5;
    private CheckBox checkBox6;
    private CheckBox checkBox7;
    private CheckBox checkBox8;
    private View preview;
    private View greenGrad;
    private View blueGrad;
    private View duskGrad;
    private View whiteBackground;
    private SeekBar opacitySeekBar;
    private Switch uiVersionSwitch;
    private LinearLayout backgroundCustomizationSection;
    private boolean isUpdating = false;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_settings);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initViews();
        setupListeners();
        loadSettings();
    }

    private void initViews() {
        checkBox1 = findViewById(R.id.checkBox1);
        checkBox2 = findViewById(R.id.checkBox2);
        checkBox3 = findViewById(R.id.checkBox3);
        checkBox4 = findViewById(R.id.checkBox4);
        checkBox5 = findViewById(R.id.checkBox5);
        checkBox6 = findViewById(R.id.checkBox6);
        checkBox7 = findViewById(R.id.checkbox7);
        checkBox8 = findViewById(R.id.checkBox8);
        greenGrad = findViewById(R.id.greenGrad);
        blueGrad = findViewById(R.id.blueGrad);
        duskGrad = findViewById(R.id.duskGrad);
        preview = findViewById(R.id.preview);
        whiteBackground = findViewById(R.id.whiteBackground);
        opacitySeekBar = findViewById(R.id.opacity_seek_bar);

        uiVersionSwitch = findViewById(R.id.ui_version_switch);
        backgroundCustomizationSection = findViewById(R.id.background_customization_section);
    }

    private void setupListeners() {
        // UI版本切换监听器
        uiVersionSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            saveUIVersionSetting(isChecked);
            if (uiVersionChangeListener != null) {
                uiVersionChangeListener.onUIVersionChanged(isChecked);
            }
            setResult(Activity.RESULT_OK);

            String message = isChecked ? "已切换到新版UI" : "已切换到经典UI";
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        });

        // 透明度滑条设置
        opacitySeekBar.setMax(255);
        // opacitySeekBar.setProgress(25); // 初始值应由 loadOpacitySetting 决定
        opacitySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int alpha = progress;
                if (preview.getBackground() != null) {
                    preview.getBackground().setAlpha(alpha);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                saveOpacitySetting(seekBar.getProgress());
            }
        });

        // 主题选择监听器
        checkBox1.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isUpdating && isChecked) {
                clearOtherCheckBoxes(checkBox1);
                applyGreenMoodTheme();
                saveThemeSetting("green_mood");
                // loadThemeSetting(); // 选择后不需要再次加载，避免循环
            }
        });

        checkBox2.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isUpdating && isChecked) {
                clearOtherCheckBoxes(checkBox2);
                applyBlueOceanTheme();
                saveThemeSetting("blue_ocean");
                // loadThemeSetting();
            }
        });

        checkBox3.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isUpdating && isChecked) {
                clearOtherCheckBoxes(checkBox3);
                applyEveningWorldTheme();
                saveThemeSetting("evening_world");
                // loadThemeSetting();
            }
        });

        checkBox8.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isUpdating && isChecked) {
                clearOtherCheckBoxes(checkBox8);
                applyModernCityTheme();
                saveThemeSetting("modern_city");
                // loadThemeSetting();
            }
        });

        // 背景选择监听器
        checkBox4.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isUpdating && isChecked) {
                clearOtherCheckBoxes2(checkBox4);
                applyGradientBackground(new int[]{0xFFE7F0C3, 0xFFA7D1AC, 0xFF3DABAA, 0xFF577982, 0xFF5A5152}, greenGrad); // 应用到greenGrad预览块
                applyGradientBackground(new int[]{0xFFE7F0C3, 0xFFA7D1AC, 0xFF3DABAA, 0xFF577982, 0xFF5A5152}, preview);   // 同时应用到主预览块
                saveBackgroundSetting("green_gradient");
                // loadBackgroundSetting(); // 选择后不需要再次加载
            }
        });

        checkBox5.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isUpdating && isChecked) {
                clearOtherCheckBoxes2(checkBox5);
                applyGradientBackground(new int[]{0xFFA1CAFF, 0xFF6A95CC, 0xFF3A4D8F, 0xFF132666, 0xFF332B3A}, blueGrad);
                applyGradientBackground(new int[]{0xFFA1CAFF, 0xFF6A95CC, 0xFF3A4D8F, 0xFF132666, 0xFF332B3A}, preview);
                saveBackgroundSetting("blue_gradient");
                // loadBackgroundSetting();
            }
        });

        checkBox6.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isUpdating && isChecked) {
                clearOtherCheckBoxes2(checkBox6);
                applyGradientBackground(new int[]{0xFFF8B195, 0xFFF67280, 0xFFC06C84, 0xFF6C5B7B, 0xFF355C7D}, duskGrad);
                applyGradientBackground(new int[]{0xFFF8B195, 0xFFF67280, 0xFFC06C84, 0xFF6C5B7B, 0xFF355C7D}, preview);
                saveBackgroundSetting("dusk_gradient");
                // loadBackgroundSetting();
            }
        });

        checkBox7.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isUpdating && isChecked) {
                clearOtherCheckBoxes2(checkBox7);
                applySolidBackground(0xFFF1F1F5); // 应用到主预览块
                saveBackgroundSetting("white_solid");
                // loadBackgroundSetting();
            }
        });

        setupBackgroundClickListeners();
        findViewById(R.id.btn_exit4).setOnClickListener(v -> finish());
    }
    public static void setOnUIVersionChangeListener(OnUIVersionChangeListener listener) {
        uiVersionChangeListener = listener;
    }

    private void setupBackgroundClickListeners() {
        // 初始化小的预览色块
        applyGradientBackground(new int[]{0xFFE7F0C3, 0xFFA7D1AC, 0xFF3DABAA, 0xFF577982, 0xFF5A5152}, greenGrad);
        applyGradientBackground(new int[]{0xFFA1CAFF, 0xFF6A95CC, 0xFF3A4D8F, 0xFF132666, 0xFF332B3A}, blueGrad);
        applyGradientBackground(new int[]{0xFFF8B195, 0xFFF67280, 0xFFC06C84, 0xFF6C5B7B, 0xFF355C7D}, duskGrad);
        // whiteBackground 通常是固定的白色，不需要动态设置背景，除非它的设计如此

        greenGrad.setOnClickListener(v -> {
            isUpdating = true; // 防止触发 checkbox 的 listener
            checkBox4.setChecked(true);
            isUpdating = false;
            clearOtherCheckBoxes2(checkBox4);
            applyGradientBackground(new int[]{0xFFE7F0C3, 0xFFA7D1AC, 0xFF3DABAA, 0xFF577982, 0xFF5A5152}, preview);
            saveBackgroundSetting("green_gradient");
        });

        blueGrad.setOnClickListener(v -> {
            isUpdating = true;
            checkBox5.setChecked(true);
            isUpdating = false;
            clearOtherCheckBoxes2(checkBox5);
            applyGradientBackground(new int[]{0xFFA1CAFF, 0xFF6A95CC, 0xFF3A4D8F, 0xFF132666, 0xFF332B3A}, preview);
            saveBackgroundSetting("blue_gradient");
        });

        duskGrad.setOnClickListener(v -> {
            isUpdating = true;
            checkBox6.setChecked(true);
            isUpdating = false;
            clearOtherCheckBoxes2(checkBox6);
            applyGradientBackground(new int[]{0xFFF8B195, 0xFFF67280, 0xFFC06C84, 0xFF6C5B7B, 0xFF355C7D}, preview);
            saveBackgroundSetting("dusk_gradient");
        });

        whiteBackground.setOnClickListener(v -> {
            isUpdating = true;
            checkBox7.setChecked(true);
            isUpdating = false;
            clearOtherCheckBoxes2(checkBox7);
            applySolidBackground(0xFFF1F1F5);
            saveBackgroundSetting("white_solid");
        });
    }

    private void loadSettings() {
        loadUIVersionSetting(); // 加载UI版本设置
        loadThemeSetting();     // 加载主题设置 (这将应用默认或已保存的主题到窗口)
        loadBackgroundSetting();// 加载背景设置 (这将应用默认或已保存的背景到 preview 视图)
        loadOpacitySetting();   // 加载透明度设置
    }



    private void saveUIVersionSetting(boolean isNewUI) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("use_new_ui", isNewUI);
        editor.apply();
    }

    private void loadUIVersionSetting() {
        boolean isNewUI = getUIVersionSetting();
        uiVersionSwitch.setChecked(isNewUI);
    }

    public static boolean getUIVersionSetting(android.content.Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        // 考虑是否让新UI成为默认
        // return preferences.getBoolean("use_new_ui", true); // 例如，默认新UI
        return preferences.getBoolean("use_new_ui", false); // 保持原样，默认经典UI
    }

    private boolean getUIVersionSetting() {
        return getUIVersionSetting(this);
    }

    private void clearOtherCheckBoxes(CheckBox selectedCheckBox) {
        isUpdating = true;
        if (selectedCheckBox != checkBox1) checkBox1.setChecked(false);
        if (selectedCheckBox != checkBox2) checkBox2.setChecked(false);
        if (selectedCheckBox != checkBox3) checkBox3.setChecked(false);
        if (selectedCheckBox != checkBox8) checkBox8.setChecked(false);
        isUpdating = false;
    }

    private void clearOtherCheckBoxes2(CheckBox selectedCheckBox) {
        isUpdating = true;
        if (selectedCheckBox != checkBox4) checkBox4.setChecked(false);
        if (selectedCheckBox != checkBox5) checkBox5.setChecked(false);
        if (selectedCheckBox != checkBox6) checkBox6.setChecked(false);
        if (selectedCheckBox != checkBox7) checkBox7.setChecked(false);
        isUpdating = false;
    }

    private void saveThemeSetting(String theme) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("theme", theme);
        editor.apply();
    }

    private void loadThemeSetting() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        // 修改点1: 将 "green_mood" 改为 "modern_city" 作为默认主题
        String theme = sharedPreferences.getString("theme", "modern_city");

        isUpdating = true;
        // 先清除所有主题复选框的选中状态
        checkBox1.setChecked(false);
        checkBox2.setChecked(false);
        checkBox3.setChecked(false);
        checkBox8.setChecked(false);

        switch (theme) {
            case "green_mood":
                checkBox1.setChecked(true);
                applyGreenMoodTheme();
                break;
            case "blue_ocean":
                checkBox2.setChecked(true);
                applyBlueOceanTheme();
                break;
            case "evening_world":
                checkBox3.setChecked(true);
                applyEveningWorldTheme();
                break;
            case "modern_city":
                checkBox8.setChecked(true);
                // 修改点2: 调用 applyModernCityTheme() 而不是 applyEveningWorldTheme()
                applyModernCityTheme();
                break;
            default: // 处理未知的或新的默认值
                checkBox8.setChecked(true); // 默认选中 modern_city
                applyModernCityTheme();
                break;
        }
        isUpdating = false;
    }

    private void applyGreenMoodTheme() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("color", 0x6AA7D1AC); // 注意，这里存储的是一个 ARGB 颜色值
        editor.apply();

        Toast.makeText(this, "绿色好心情~", Toast.LENGTH_SHORT).show();
        getWindow().getDecorView().setBackgroundColor(0xFFA7D1AC); // 使用与存储的颜色匹配的颜色
    }

    private void applyBlueOceanTheme() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("color", 0x6ACFF3EA);
        editor.apply();

        Toast.makeText(this, "这片海域很干净~", Toast.LENGTH_SHORT).show();
        getWindow().getDecorView().setBackgroundColor(0xFFCFF3EA);
    }

    private void applyEveningWorldTheme() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("color", 0x6A355C7D);
        editor.apply();

        Toast.makeText(this, "人间忽晚，山河已秋", Toast.LENGTH_SHORT).show();
        getWindow().getDecorView().setBackgroundColor(0xFF355C7D);
    }
    private void applyModernCityTheme() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        // 获取 R.color.color1_6 实际的颜色值
        int actualColor = ContextCompat.getColor(this, R.color.color1_6);
        editor.putInt("color", actualColor); // <--- 存储实际颜色值
        editor.apply();

        Toast.makeText(this, "现代都市~", Toast.LENGTH_SHORT).show();
        getWindow().getDecorView().setBackgroundColor(actualColor);
    }
    private void saveBackgroundSetting(String background) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("background", background);
        editor.apply();
    }

    private void loadBackgroundSetting() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String background = sharedPreferences.getString("background", "white_solid"); // 默认背景

        isUpdating = true;
        // 先清除所有背景复选框的选中状态
        checkBox4.setChecked(false);
        checkBox5.setChecked(false);
        checkBox6.setChecked(false);
        checkBox7.setChecked(false);

        switch (background) {
            case "green_gradient":
                checkBox4.setChecked(true);
                // applyGradientBackground(new int[]{0xFFE7F0C3, 0xFFA7D1AC, 0xFF3DABAA, 0xFF577982, 0xFF5A5152}, greenGrad); // 只更新小预览块
                applyGradientBackground(new int[]{0xFFE7F0C3, 0xFFA7D1AC, 0xFF3DABAA, 0xFF577982, 0xFF5A5152}, preview); // 更新大预览块
                break;
            case "blue_gradient":
                checkBox5.setChecked(true);
                // applyGradientBackground(new int[]{0xFFA1CAFF, 0xFF6A95CC, 0xFF3A4D8F, 0xFF132666, 0xFF332B3A}, blueGrad);
                applyGradientBackground(new int[]{0xFFA1CAFF, 0xFF6A95CC, 0xFF3A4D8F, 0xFF132666, 0xFF332B3A}, preview);
                break;
            case "dusk_gradient":
                checkBox6.setChecked(true);
                // applyGradientBackground(new int[]{0xFFF8B195, 0xFFF67280, 0xFFC06C84, 0xFF6C5B7B, 0xFF355C7D}, duskGrad);
                applyGradientBackground(new int[]{0xFFF8B195, 0xFFF67280, 0xFFC06C84, 0xFF6C5B7B, 0xFF355C7D}, preview);
                break;
            case "white_solid":
            default: // 如果找不到或者就是 white_solid
                checkBox7.setChecked(true);
                applySolidBackground(0xFFF1F1F5); // 应用到主预览块
                break;
        }
        isUpdating = false;
    }

    private void applyGradientBackground(int[] colors, View view) {
        GradientDrawable gradientDrawable = new GradientDrawable(
                GradientDrawable.Orientation.TOP_BOTTOM, colors);
        view.setBackground(gradientDrawable);
        // 确保透明度在应用新背景后仍然生效
        loadOpacitySetting(); // 或者直接从 SharedPreferences 读取并应用透明度
    }

    private void applySolidBackground(int color) {
        preview.setBackgroundColor(color);
        // 确保透明度在应用新背景后仍然生效
        loadOpacitySetting(); // 或者直接从 SharedPreferences 读取并应用透明度
    }

    private void saveOpacitySetting(int opacity) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt("background_opacity", opacity);
        editor.apply();
    }

    private void loadOpacitySetting() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        int savedOpacity = preferences.getInt("background_opacity", 255); // 默认完全不透明或一个合理的初始值
        if (preview.getBackground() != null) {
            preview.getBackground().setAlpha(savedOpacity);
        }
        opacitySeekBar.setProgress(savedOpacity);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        uiVersionChangeListener = null;
    }

    // 确保你有这个接口定义，或者它在其他地方定义
    public interface OnUIVersionChangeListener {
        void onUIVersionChanged(boolean isNewUIVersion);
    }
}